<template>
  <div class="table-inline-editor">
    <!-- 编辑模式显示对应编辑组件 -->
    <template v-if="isEditing">
      <!-- 针对不同类型组件进行特殊处理 -->
      <template v-if="componentType === 'select'">
        <el-select
          v-model="localValue"
          :validate-event="false"
          :class="['edit-component', { 'error': finalErrorMessage }]"
          v-bind="componentProps"
          @change="handleInput"
          placeholder="请选择"
          @blur="handleBlur"
        >
          <!-- 动态渲染选项 -->
          <el-option v-for="option in componentProps.options" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </template>
      <template v-else-if="componentType === 'switch'">
        <!-- 开关组件特殊处理 -->
        <el-switch v-model="localValue" v-bind="componentProps" @change="handleInput" @blur="handleBlur" />
      </template>
      <!-- 为时间选择器添加width: 100%的样式 -->
      <template v-else-if="componentType === 'time-picker'">
        <div :class="['edit-component-container', { 'error': finalErrorMessage }]">
          <el-time-picker
            v-model="localValue"
            :validate-event="false"
            v-bind="{ ...componentProps, style: { width: '100%' } }"
            @change="handleInput"
            @blur="handleBlur"
            @close="handleBlur"
            clearable
          />
        </div>
      </template>
      <template v-else-if="componentType === 'date-picker'">
        <div :class="['edit-component-container', { 'error': finalErrorMessage }]">
          <el-date-picker
            v-model="localValue"
            :validate-event="false"
            v-bind="{ ...componentProps, style: { width: '100%' } }"
            @change="handleInput"
            @blur="handleBlur"
            @close="handleBlur"
            clearable
          />
        </div>
      </template>
      <template v-else-if="componentType === 'text-only'">
        <span class="ellipsis-text">
          {{ displayValue || '-' }}
        </span>
      </template>
      <template v-else>
        <!-- 其他组件使用通用方式 -->
        <el-input
          :is="componentType"
          v-model="localValue"
          :validate-event="false"
          clearable
          placeholder="请输入"
          :class="['edit-component', { 'error': finalErrorMessage }]"
          v-bind="componentProps"
          @input="handleInput"
          @blur="handleBlur"
        />
      </template>
      <!-- 显示验证错误信息 -->
      <div v-if="finalErrorMessage" class="error-message">
        {{ finalErrorMessage }}
      </div>
    </template>
    <!-- 非编辑模式显示文本 -->
    <span v-else class="ellipsis-text">
      <span> {{ displayValue || '-' }}</span>
    </span>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { ColorForm } from '@/api/erpbase/color/types';

const props = defineProps<{
  modelValue: any;
  row: ColorForm;
  column: {
    prop: string;
    label: string;
  };
  isEditing: boolean;
  errorMessage: string;
  componentType: string;
  componentProps: Record<string, any>;
  readOnly?: boolean;
  rules?: any; // 修改这一行
}>();

// Emits definition using Vue 3's update:modelValue convention
const emit = defineEmits<{
  'update:modelValue': [value: any];
  'click': [];
  'blur': [];
  'input': [value: any];
  'validate': [error: string];
}>();
// 本地值，用于双向绑定
const localValue = ref<any>(props.modelValue);
// 本地错误信息，用于失焦验证
const localError = ref<string>('');

// 监听props.modelValue变化，更新本地值
watch(
  () => props.modelValue,
  (newVal) => {
    localValue.value = newVal;
  },
  { deep: true }
);
// 监听外部errorMessage变化，同步到本地
watch(
  () => props.errorMessage,
  (newError) => {
    localError.value = newError;
  }
);

// 计算显示值（处理布尔值等特殊情况）
const displayValue = computed(() => {
  if (props.componentType === 'el-switch') {
    return props.modelValue ? '是' : '否';
  }
  return props.modelValue;
});
// 计算最终显示的错误信息
const finalErrorMessage = computed(() => {
  return localError.value || props.errorMessage;
});
// 字段验证函数
const validateField = (value: any, fieldName: string): string => {
  if (!props.rules || !props.rules[fieldName]) return '';

  const fieldRules = props.rules[fieldName];
  for (const rule of fieldRules) {
    // 处理必填验证
    if (rule.required && (!value || (typeof value === 'string' && value.trim() === ''))) {
      return rule.message;
    }
  }
  return '';
};

// 处理输入变化
const handleInput = (value: any) => {
  localValue.value = value;
  emit('update:modelValue', value);
  emit('input', value);
  // 输入时清除错误提示
  if (localError.value) {
    localError.value = '';
    emit('validate', '');
  }
};

// 处理失焦事件
const handleBlur = () => {
  // 执行验证逻辑
  const error = validateField(localValue.value, props.column.prop);
  localError.value = error;
  emit('validate', error);
  emit('blur');
};
</script>

<style scoped>
.table-inline-editor {
  position: relative;
  width: 100%;
}

.edit-component,
.edit-component-container {
  width: 100%;
}

/* 使用CSS变量替代硬编码颜色值 */
.edit-component.error,
.edit-component-container.error {
  --el-border-color: var(--el-color-danger);
  --el-border-color-hover: var(--el-color-danger);
  --el-input-border-color: var(--el-color-danger);
  --el-input-focus-border-color: var(--el-color-danger);
  --el-select-border-color: var(--el-color-danger);
  --el-select-focus-border-color: var(--el-color-danger);
  animation: error-shake 0.3s ease-in-out;
}

/* 使用:deep()选择器确保样式穿透到date-picker和time-picker内部组件 */
.edit-component-container.error :deep(.el-input__wrapper),
.edit-component.error :deep(.el-input__wrapper) {
  --el-input-border-color: var(--el-color-danger);
  --el-input-focus-border-color: var(--el-color-danger);
  border-color: var(--el-color-danger) !important;
  box-shadow: 0 0 0 1px var(--el-color-danger) inset;
}

/* 针对date-picker特殊处理 */
.edit-component-container.error :deep(.el-date-editor),
.edit-component.error :deep(.el-date-editor) {
  --el-date-editor-border-color: var(--el-color-danger);
  border-color: var(--el-color-danger) !important;
}

.edit-component-container.error :deep(.el-date-editor__input),
.edit-component.error :deep(.el-date-editor__input) {
  --el-date-editor-border-color: var(--el-color-danger);
  border-color: var(--el-color-danger) !important;
}

/* 为select和input等其他组件保留原有样式 */
.edit-component.error {
  border-color: var(--el-color-danger) !important;
}

/* 保留错误提示的抖动动画 */
@keyframes error-shake {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-4px);
  }
  75% {
    transform: translateX(4px);
  }
}

/* 其余样式保持不变 */
.error-message {
  color: #fff;
  background-color: var(--el-color-danger);
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1000;
  white-space: nowrap;
  margin-top: 4px;
  max-width: 200px;
  word-wrap: break-word;
  word-break: break-all;
}

.error-message::before {
  content: '';
  position: absolute;
  top: -4px;
  left: 8px;
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-bottom: 4px solid var(--el-color-danger-light-7);
}

.ellipsis-text {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
